<template>
  <DetailsFormBox :title="page.title" :type="route.query.type" :form="data.form" :btns="[
    {
      title: '重置',
      icon: '',
      type: '',
      hidden: !isEdit,
      click: getForm,
    },
    {
      title: '仅保存',
      icon: '',
      type: 'primary',
      hidden: !isEdit,
      click: (form: any) => {
        saveBtn(form, false)
      },
    },
    {
      title: '保存并确认',
      icon: '',
      type: 'primary',
      hidden: !isEdit,
      click: (form: any) => {
        saveBtn(form, true)
      },
    },
  ]" :formInfo="[
    {
      label: '创建人员',
      value: 'createByName',
    },
    {
      label: '创建时间',
      value: 'createTime',
    },
  ]" :loading="data.loading" :loadingMsg="data.loadingMsg">
    <template #default="{ form }">
      <div class="p-12">
        <OrderInfo :data="data.productOrder" :produceTaskBillNo="route.query.produceTaskBillNo" />
        <CellBox title="基本信息" isTop>
          <FlexBox>
            <ElFormItemBox label="单据单号" prop="scrapBillNo">
              <ElInputBox :data="form" dataName="scrapBillNo" placeholder="系统自动生成" disabled />
            </ElFormItemBox>
            <ElFormItemBox label="单据状态" prop="scrapBillState">
              <ElSelectBox :data="form" dataName="scrapBillState" :options="options.state" disabled />
            </ElFormItemBox>
            <ElFormItemBox label="报废日期" prop="scrapBatchDate" isRules>
              <ElDayBox :data="form" dataName="scrapBatchDate" :disabled="!isEdit" @changeBtn="(value: any) => {
                addSelect.search.endProductionDate = value
              }" />
            </ElFormItemBox>
            <ElFormItemBox label="单据备注" prop="scrapRemark" class="wAuto">
              <ElInputBox :data="form" dataName="scrapRemark" type="textarea" :disabled="!isEdit" />
            </ElFormItemBox>
            <ElFormItemBox label="红冲原因" prop="redStrikeRemark" class="wAuto" v-if="!!form.redStrikeRemark">
              <ElInputBox :data="form" dataName="redStrikeRemark" type="textarea" disabled />
            </ElFormItemBox>
          </FlexBox>
        </CellBox>
        <CellBox title="单据明细" isTop>
          <GoodList :data="{
            disabled: !isEdit,
            height: 450,
            rowKey: 'specificationCode',
            prop: 'mxDataList',
            tbody: form.mxDataList,
            thead: [
              {
                label: '生产批次',
                prop: 'productionBatchNumber',
                disabled: true,
              },
              {
                label: '生产日期',
                prop: 'productionDate',
                disabled: true,
              },
              {
                label: '所在仓库',
                prop: 'wareHouseAreaSheltName',
                disabled: true,
              },
              {
                label: '库存数量',
                prop: 'stockQuantity',
              },
              {
                label: '报废数量',
                prop: 'scrapQuantity',
                formType: 'number',
                isRules: true,
                changeBtn: (value: any, row: any) => {
                  if (value > row.stockQuantity) {
                    proxy.$message('出库数量不能大于库存数量', 'error');
                    row.outStockQuantity = row.stockQuantity
                  }
                },
              },
              {
                label: '备注',
                prop: 'scrapDetailRemark',
                formType: 'textarea'
              },
            ],
            operation: [
              {
                label: '删除',
                icon: 'Delete',
              },
            ],
            addSelect: addSelect,
          }" @selectBtn="addMx" @searchBtn="searchMxBtn">
            <template #search="{ search }">
              <ElFormItemBox label="物料名称">
                <ElInputBox :data="search" dataName="likeWords" />
              </ElFormItemBox>
              <ElFormItemBox label="物料类型">
                <ElSelectBox :data="search" dataName="groupCode" :options="options.goodGroup" />
              </ElFormItemBox>
              <ElFormItemBox label="供应商">
                <ElSelectBox :data="search" dataName="supplierCode" :options="options.supplier" />
              </ElFormItemBox>
              <ElFormItemBox label="批次日期">
                <ElDayBox :data="search" dataName="endProductionDate" disabled />
              </ElFormItemBox>
            </template>
          </GoodList>
        </CellBox>
      </div>
    </template>
  </DetailsFormBox>
</template>
<script setup lang="ts">
import { sendMsg } from '@/utils/crossTagMag.ts';
import { useListComponent } from '../pageTs'; // 引入逻辑
import page from '../page.ts'; // 引入逻辑
import '../pageCss.scss'; // 引入样式
const { dataInfo, options } = useListComponent();
const { proxy } = getCurrentInstance() as any;
const data: any = reactive({
  loading: false,
  loadingMsg: '',
  mainPage: 1,
  form: {
    scrapBillID: 0, // 报废单ID
    scrapBillCode: "", // 报废单唯一编码
    scrapBillNo: "", // 报废单号
    scrapBillState: 0, // 单据状态：0待确认；1已确认；2已作废；3已红冲
    scrapBatchDate: proxy.$getTimeAgo(1, 'years'), // 报废批次日期
    scrapRemark: "", // 报废备注
    redStrikeRemark: "", // 红冲原因
    createTime: "", // 创建时间，格式：yyyy-MM-dd HH:mm:ss
    createBy: "", // 创建人员代码
    createByName: "", // 创建人员姓名
    mxDataList: []
  },
});
const isEdit = ref(true)
const addSelect: any = reactive({
  title: '申请明细',
  rowKey: 'stockGoodsCode',
  loading: false,
  search: {
    stockGoodsCode: "", // 库存唯一编码，空值查全部
    groupCode: "", // 分组代码，空值查询全部
    categoryCode: "", // 分类代码，空值查询全部
    supplierCode: "", // 供应商代码，空值查询全部
    goodsCode: "", // 基础物料代码，空值查询全部
    likeWords: "", // 查询关键字，空值查询全部
    endProductionDate: "" // 最后生产批次日期
  },
  thead: [
    {
      label: '物料编号',
      prop: 'specificationCode',
      align: 'center',
      width: 120,
    },
    {
      label: '物料名称',
      prop: 'goodsName',
      align: 'left',
      width: null,
    },
    {
      label: '规格型号',
      prop: 'specificationName',
      align: 'center',
      width: 120,
    },
    {
      label: '类型',
      prop: 'groupName',
      align: 'center',
      width: 120,
    },
    {
      label: '供应商',
      prop: 'supplierName',
      align: 'center',
      width: 260,
    },
    {
      label: '生产日期',
      prop: 'productionDate',
      align: 'center',
      width: 120,
    },
    {
      label: '批次号',
      prop: 'productionBatchNumber',
      align: 'center',
      width: 120,
    },
    {
      label: '所属仓库',
      prop: 'warehouseAreaShelf',
      align: 'center',
      width: 120,
    },
    {
      label: '数量',
      prop: 'stockSumQuantity',
      align: 'center',
      width: 120,
    },
    {
      label: '单位',
      prop: 'goodsUnitName',
      align: 'center',
      width: 120,
    },
  ],
  tbody: [],
})
//添加关联单明细
const searchMxBtn = () => {
  addSelect.loading = true
  addSelect.search.endProductionDate = data.form.scrapBatchDate
  proxy.$api.Warehouse.GetMatchStockGoodsDataList(addSelect.search)
    .then((res: any) => {
      addSelect.tbody = res.map((el: any) => ({
        ...el,
        productionDate: proxy.$day(el.productionDate)
      }))
      addSelect.loading = false
    })
    .catch(() => {
      addSelect.loading = false
    });
}
//添加关联单明细
const addMx = (rows: any) => {
  const _rows = Array.isArray(rows) ? rows : [rows]
  let _arr = _rows.map((el: any) => {
    return {
      goodsCode: el.goodsCode,// 物料编号
      supplierCode: el.supplierCode, // 供应商编码
      specificationCode: el.specificationCode, // 物料规格编码
      productionBatchCode: el.productionBatchCode,//	生产批次编码
      productionBatchNumber: el.productionBatchNumber,//	生产批次号
      productionDate: el.productionDate ? proxy.$day(el.productionDate) : '',//	生产日期
      warehouseAreaCode: el.warehouseAreaCode,//	仓库分区代码
      areaShelfCode: el.areaShelfCode,//	仓库分区代码
      wareHouseAreaSheltName: el.warehouseAreaShelf,//	所在仓房哭
      stockGoodsCode: el.stockGoodsCode,//	物料规格库存代码
      scrapQuantity: el.stockQuantity,//	报废数量
    }
  })
  data.form.mxDataList.push(
    ..._arr
  )
}
import { useRoute } from 'vue-router';
// 获取当前路由对象
const route = useRoute();
//获取数据
const getForm = async () => {
  const _query: any = route.query
  setLoading()
  //是否新建
  if (!!!_query.code) {
    data.loading = false
    return
  }
  proxy.$api.GoodsScrapBill.GetGoodsScrapBillDetail({
    code: _query.code,
  })
    .then((res: any) => {
      proxy.$message('获取成功')
      isEdit.value = ['1', '2'].includes(_query.type) && res.baseData.scrapBillState === 0
      data.form = {
        ...res.baseData,
        mxDataList: res.mxDataList.map((el: any) => ({
          ...el,
          productionDate: proxy.$day(el.productionDate)
        })),
      }
      data.loading = false
    })
    .catch(() => {
      data.loading = false
    });
};
const saveBtn = (form: any, isConfirm: boolean = false, isPartial?: number) => {
  // return
  switch (route.query.type) {
    case '1'://新建
      proxy.$api.GoodsScrapBill.CreateNewGoodsScrapBill({
        scrapRemark: form.scrapRemark,//报废备注说明
        scrapBatchDate: form.scrapBatchDate,//报废批次日期
        goodsScrapBillDetailList: form.mxDataList.map((el: any) => ({
          stockGoodsCode: el.stockGoodsCode,//物料规格库存代码
          scrapQuantity: el.scrapQuantity,//报废数量
          scrapDetailRemark: el.scrapDetailRemark,//报废备注说明
        }))
      })
        .then((res: any) => {
          if (isConfirm) {
            _setState(res)
          } else {
            _sun()
          }
        })
        .catch(() => {
        });
      break;
    case '2'://编辑
      proxy.$api.GoodsScrapBill.UpdateGoodsScrapBill({
        scrapBillCode: form.scrapBillCode,//报废备注说明
        scrapRemark: form.scrapRemark,//报废备注说明
        scrapBatchDate: form.scrapBatchDate,//报废批次日期
        scrapMxDataList: form.mxDataList.map((el: any) => ({
          stockGoodsCode: el.stockGoodsCode,//物料规格库存代码
          scrapQuantity: el.scrapQuantity,//报废数量
          scrapDetailRemark: el.scrapDetailRemark,//报废备注说明
        }))
      })
        .then((res: any) => {
          if (isConfirm) {
            _setState(form.scrapBillCode)
          } else {
            _sun()
          }
        })
        .catch(() => {
        });
      break;
    default:
      break;
  }
  function _sun() {
    closeBtn('保存成功')
  }
  function _setState(code: string) {
    setState(code)
  }
};
const closeBtn = (message?: string) => {
  if (message) {
    proxy.$message(message)
  }
  sendMsg('save', true);
  // getForm()
  window.close();
};
const setState = (code: string) => {
  proxy.$api.GoodsScrapBill.SureGoodsScrapBill({
    code: code,
  })
    .then((res: any) => {
      closeBtn('保存成功')
    })
    .catch(() => {
      closeBtn()
    });
};
const setLoading = (title: string = '正在获取数据,请稍等...') => {
  if (!data.loading) {
    data.loading = true;
    data.loadingMsg = title;
  }
};

import { getSupplier, goodGroup } from '@/utils/optionsArr.ts';
onMounted(() => {
  getForm();
  getSupplier(options, 'supplier')//获取供应商
  goodGroup(options, 'goodGroup')//获取类型
});
</script>
